<?php
namespace backend\controllers;

use backend\modules\business\models\BusinessPig;
use common\components\Upload;
use common\models\business\BusinessContract;
use common\models\business\BusinessFarmers;
use common\models\business\BusinessInspection;
use common\models\business\BusinessUser;
use common\models\business\BusinessUserNotice;
use common\models\shop\ShopOrder;
use izyue\admin\models\Log;
use Yii;
use yii\db\Expression;
use yii\db\Query;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use backend\models\LoginForm;
use common\models\sys\SysSetting;
use backend\controllers\AdminController;
/**
 * Site controller
 */
class SiteController extends AdminController
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['login', 'error','captcha'],
                        'allow' => true,
                    ],
                    [
                        'actions' => ['logout', 'index','attr-delete','sortfile'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                //'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
                //'backColor'=>0x000000,//背景颜色
                'maxLength' => 4, //最大显示个数
                'minLength' => 4,//最少显示个数
                //'padding' => 5,//间距
                'height'=>60,//高度
                'width' => 100,  //宽度
                // 'foreColor'=>0xffffff,     //字体颜色
                //'offset'=>4,        //设置字符偏移量 有效果
                //'controller'=>'login',        //拥有这个动作的controller
            ],
        ];
    }

    public function actionIndex()
    {

        $count = [];
        $count['usercount']  = (new Query())->select('*')->from(BusinessUser::tableName())->count();
        $count['farmercount']  = (new Query())->select('*')->from(BusinessFarmers::tableName())->count();
        $count['ordercount']  = (new Query())->select('*')->from(ShopOrder::tableName())->count();
        $count['pigcount']  = (new Query())->select('*')->from(BusinessPig::tableName())->count();

//        取出总粉丝
//        (new Query())->select()


        $msg = (new Query())->select(['id','title','FROM_UNIXTIME(createtime,"%Y-%m-%d %H:%i:%s") as time','level'])
            ->from(BusinessUserNotice::tableName())
            ->where('status=:status',[':status'=>BusinessUserNotice::STATUS_PUBLISH])
            ->all();


        //取出最近的操作
//        $logs  = (new Query())->select('route,created_at,gets,ip,user_agent')
//            ->from(Log::tableName())
//            ->where('admin_id=:uid',[':uid'=>Yii::$app->user->id])
//            ->orderBy('id desc')
//            ->limit(30)
//            ->all();
//
//        $colors = ['blue','red','green','purple'];
//        foreach ($logs as $key => $row){
//            $logs[$key]['time'] = date('H:i a',$row['created_at']);
//            $logs[$key]['date'] = date('Y-m-d | l',$row['created_at']);
//            $logs[$key]['alt'] = $key%2!=0?'alt':'';
//            $logs[$key]['color'] = $colors[rand(0,3)];
//        }


        //取出即将预出栏的猪仔
        $preday = SysSetting::getValue('waitout');
        $planoutpigs = (new Query())->select('id,no,planout,headperson,liveryname,intime')
            ->from(BusinessPig::tableName())
            ->where('planout != 0 and planout-:preday<=:now',[':preday'=>$preday*3600*24,':now'=>time()])
            ->limit(10)
            ->all();
        foreach ($planoutpigs as $key => $row){
            $planoutpigs[$key]['planout'] = date('Y-m-d',$row['planout']);
            $planoutpigs[$key]['intime'] = date('Y-m-d',$row['intime']);
        }

        $planoutcount = (new Query())->select(new Expression('count(id) as count'))
            ->from(BusinessPig::tableName())
            ->where('planout != 0 and planout-:preday<=:now',[':preday'=>$preday*3600*24,':now'=>time()])
            ->scalar();



        //取出即将到期的合同
        $now = time();
        $setouttime = SysSetting::getValue('contract_out_time');
        $outcontract = (new Query())->select('id,name,no,partyA,partyB,start_time,end_time')
            ->from(BusinessContract::tableName())
            ->where('end_time!=0 and end_time<=:outdate and end_time>=:now',[':outdate'=>$setouttime*3600*24+$now,':now'=>time()])
            ->limit(10)
            ->all();

        $outcontractout = (new Query())->select(new Expression('count(id)'))
            ->from(BusinessContract::tableName())
            ->where('end_time!=0 and end_time<=:outdate and end_time>=:now',[':outdate'=>$setouttime*3600*24+$now,':now'=>time()])
            ->scalar();



        return $this->render('index',[
            'count' => $count,
            'msg' => $msg,
            'planoutpigs' => $planoutpigs,
            'outcontract' => $outcontract,
            'planoutcount' => $planoutcount,
            'outcontractout' => $outcontractout
        ]);
    }

    public function actionLogin()
    {
        
        $this->layout = 'login.php';
        if (!Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
            return $this->goBack();
        } else {
            
//             echo 123;exit;
            return $this->render('login', [
                'model' => $model,
            ]);
        }
    }

    public function actionLogout()
    {
        Yii::$app->user->logout();

        return $this->goHome();
    }


    public function actionAttrDelete($path)
    {
        $postdata = Yii::$app->request->post();
        $filed = Yii::$app->db->createCommand('select '.$postdata['field'].' from '.$postdata['table'].' where '.$postdata['idname'].'=:id')
            ->bindValues([':id'=>$postdata['id']])
            ->queryScalar();
        if(strpos($filed,Upload::$mutidi) !== false) {
            $fileds = explode(Upload::$mutidi,$filed);
            foreach ($fileds as $key => $row){
                if($path == Upload::checkGetPath($row,$postdata['field'])){
                    unset($fileds[$key]);
                }
            }
            $udata = implode(Upload::$mutidi,$fileds);
        }else{
            $udata = '';
        }
        Yii::$app->db->createCommand()->update($postdata['table'],[$postdata['field']=>$udata],$postdata['idname'].'=:id',[':id'=>$postdata['id']])->execute();

        if(is_file($path) && file_exists($path)){
            if(unlink($path)){
                return \GuzzleHttp\json_encode(['ok']);
            }
        }
        return \GuzzleHttp\json_encode(['false']);

    }


    /**
     * 排序
     */
    public function actionSortfile()
    {

        $postdta = Yii::$app->request->post();

        foreach ($postdta['data'] as $key => $val){
            $path[] = substr($val['path'],strlen(Yii::getAlias('@uploadpath'))+1);
        }
        if(empty($path)){
            return \GuzzleHttp\json_encode(['msg'=>'图片为空','status'=>1]);
        }
        $upd = $postdta['data'][0];
        $pathdata = implode(Upload::$mutidi,$path);
        $res = Yii::$app->db->createCommand()->update($upd['table'],[$upd['field']=>$pathdata],$upd['idname'].'=:id',[':id'=>$upd['id']])
            ->execute();

        return $res?\GuzzleHttp\json_encode(['msg'=>'排序成功','status'=>0]):\GuzzleHttp\json_encode(['msg'=>'图片为空','status'=>1]);
    }




}
